import Common from "../Common";
import TaskItem from "./TaskItem";


const {ccclass, property} = cc._decorator;

/**
 * 今日任务弹框
 */
@ccclass
export default class Tasks extends Common {

    @property({
        type: cc.Node,
        displayName: '内容区域容器'
    })
    content: cc.Node

    protected taskItem: cc.Prefab


    protected watch = {
        tasks: async (tasks) => {
            await this.init(tasks)
        }
    }

    protected onEnable() {
        this.initTasks()
    }

    async init(tasks: any[] = []) {
        const taskItemPrefab = await this.getItem();
        await this.content.removeAllChildren(true)
        tasks.forEach(item => {
            const goodItem = cc.instantiate(taskItemPrefab)
            goodItem.getComponent(TaskItem).init({
                ...item,
                target: this,
                onClick: this.onClick,
            });
            this.content.addChild(goodItem)
        })
    }

    async onClick(id, key) {
        const KEY_SIGN = 'sign'; // 签到
        const KEY_FERTILIZE = 'fertilize'; // 施肥
        const KEY_DEWORMING = 'deworming'; // 驱虫
        const KEY_WATERING = 'watering'; // 浇水
        switch (key) {
            case KEY_SIGN:
                await this.onJiaoShuiTashComplete(KEY_SIGN)
                break;
            case KEY_FERTILIZE:
                this.showToast('点击左下角的肥料包即可进行施肥')
                break;
            case KEY_DEWORMING:
                this.showToast('存在虫子时可通过左下角的杀虫剂进行除虫')
                break;
            case KEY_WATERING:
                this.showToast('点击右下角的水壶即可进行浇水')
                break;
        }
        this.node.active = false;
    }

    initTasks() {
        this.http.get('tasks/lists').then(({data}) => {
            this._data.tasks = data
        }).catch(console.log)
    }

    protected async getItem() {
        if (!this.taskItem) {
            this.taskItem = await this.getPrefab('taskItem')
        }
        return this.taskItem
    }

    private async onJiaoShuiTashComplete(key: string) {
        try {
            const {message} = await this.http.post('tasks/complete', {key})
            this.showToast(message)
            this.initTasks()
        } catch ({message}) {
            this.showToast(message)
        }
    }
}
